import { _decorator, animation, Button, CCFloat, clamp, Component, instantiate, Label, labelAssembler, Node, resources,Animation, randomRange, randomRangeInt ,EventTarget, Vec3, tween, easing, Camera, quat, Quat, AudioSource, AudioClip, view,screen} from 'cc';
import { Actor } from './Actor';
import { ResourceManager } from '../PlayableFramework/Tools/Manager/ResourceManager';
import { CONSTANTFORCE } from '../../extensions/plugin-import-2x/creator/components/ConstantForce';
import ads, { AdsManager } from '../PlayableFramework/Ads/AdsManager';
import { Room } from './Room';

const { ccclass, property } = _decorator;

@ccclass('Scene')
export class Scene extends Component {

    public static instance:Scene;

    @property
    public money:number = 0;

    @property(Label)
    public moneyTxt:Label;

    @property([Button])
    public btnListSP:Button[]=[];

    @property([Button])
    public btnListHP:Button[]=[];

    @property([CCFloat])
    public addRoomLevelPriceList:number[]=[];

    @property([CCFloat])
    public addRoomCountPriceList:number[]=[];

    @property([Room])
    public rooms: Room[]; // 用来配置多个 Room 脚本的数组

    public count: number = 0; // 控制 Room 数量的配置，默认值为 0

    public level: number = 0; // 控制每个 Room 的 level，默认值为 0

    public actorList:Actor[] = [];

    @property(Node)
    public storePanel:Node;

    public eventTarget = new EventTarget();

    @property(Node)
    public sp:Node;

    @property(Node)
    public hp:Node;


    protected onLoad(): void {
        Scene.instance = this;

    }

    private prefabCount = 2;
    start() {
        ads.init();
        this.storePanel.active = false;
        this.startGuidTip.active = true;
        var loader = ResourceManager.load(()=>
            {
                this.InitActorList();
                this.setRoomLevel(1);
                this.setRoomCount(1);
            }).add("MoneyEffect").add("FixBar").add("UpgradeEffect").add("Tips");
        for (let i = 1; i <= this.prefabCount; i++) {
            loader.add("UIActor"+i);
        }

        this.eventTarget.on("addMoney",(event)=>{
            this.money += event.money;
            var effect = ResourceManager.spawn("MoneyEffect",ResourceManager.getPoolNode("爆钱Parent"));
            effect.node.worldPosition = event.pos;
        });

        if(screen.windowSize.width > screen.windowSize.height){
            this.cameraPoints = ResourceManager.getPoolNode("横屏相机点");
        }
        else{
            this.cameraPoints = ResourceManager.getPoolNode("竖屏相机点");
        }
    }


    protected update(dt: number): void {

        var btnList = this.btnListSP;
        if(screen.windowSize.width > screen.windowSize.height){
            btnList = this.btnListHP;
            this.hp.active = true;
            this.sp.active = false;
        }
        else
        {
            this.hp.active = false;
            this.sp.active = true;
        }


        this.moneyTxt.string = this.money.toString();

        var addRoomLevelPrice = this.addRoomLevelPriceList[this.level];
        var addRoomCountPrice = this.addRoomCountPriceList[this.count];

        let boo :boolean[]=[];

        boo[0] = this.money >= 1 && !this.isFull();
        boo[1] = this.money >= addRoomLevelPrice;
        boo[2]= this.money >= addRoomCountPrice;

        for (let i = 0; i < btnList.length; i++) {
            const btn = btnList[i];
            btn.node.children[0].active = boo[i];
            btn.node.children[1].active = !boo[i];
        }

        btnList[1].node.children[2].children[0].getComponent(Label).string = addRoomLevelPrice.toString();
        btnList[2].node.children[2].children[0].getComponent(Label).string = addRoomCountPrice.toString();
    }

    /**
     * 设置每个 Room 的 level
     * @param level 每个 Room 的层级
     */
    public setRoomLevel(level: number) {
        this.level = clamp(level ,0, 3);
        console.log("场景等级为:"+this.level);
        this.updateRooms();
    }

    public setRoomCount(count:number){
        this.count = clamp(count ,0, this.rooms.length);
        console.log("房间数量为:"+this.count);
        this.updateRooms();
        this.cameraMove();
    }

    /**
     * 更新每个 Room 的 level
     */
    private updateRooms() {
        for (let i = 0; i < this.rooms.length; i++) {
            const room = this.rooms[i];
            room.bindEventTarget(this.eventTarget);
            if (i < this.count) {
                room.setLevel(this.level);
            } else {
                room.hideLevel()
            }
        }
    }

    @property(Node)
    public startGuidTip:Node
    public addActor()
    {
        this.startGuidTip.active = false;
        if(this.money < 1)
        {
            this.showTips("Not enough cash!");
            return;
        }

        var actor = this.actorList[0];
        var isSuccess = false;
        for (let i = 0; i < this.rooms.length; i++) {
            if(this.rooms[i].level!=0)
            {
                if(this.rooms[i].addActor(actor,i))
                {
                    this.shiftActor();
                    isSuccess = true;
                    break;
                }
            }
        }

        if(!isSuccess)
        {
            this.showTips("Short on mechanics!");
            console.log("满了满了");
        }
        else
        {
            this.money-=1;
            this.eventTarget.emit("upgradeAny");

            this.clickAudio.volume = 1;
            this.clickAudio.playOneShot(this.audioClips[0],1);
        }
    }
    
    public addRoomCount()
    {

        var addRoomCountPrice = this.addRoomCountPriceList[this.count];
        if(this.money >= addRoomCountPrice)
        {
            if(this.count < 3)
            {
                this.setRoomCount(this.count + 1);
                this.money -=addRoomCountPrice;
                this.eventTarget.emit("upgradeAny");
                this.clickAudio.volume = 1;
                this.clickAudio.playOneShot(this.audioClips[3],1);

            }
            else
            {
                this.storePanel.active = true;
                ads.end();
            }
        }
        else
        {
            this.showTips("Not enough cash!");
        }
    }
    
    @property(AudioSource)
    public clickAudio:AudioSource;

    @property([AudioClip])
    public audioClips:AudioClip[] = [];
    public addRoomLevel()
    {   

        var addRoomLevelPrice = this.addRoomLevelPriceList[this.level];
        if(this.money >= addRoomLevelPrice)
        {
            if(this.level < 3)
            {
                this.setRoomLevel(this.level + 1);
                this.money -=addRoomLevelPrice;
                this.eventTarget.emit("upgradeAny");
                this.clickAudio.volume = 1;
                this.clickAudio.playOneShot(this.audioClips[2],1);

            }
            else
            {
                this.storePanel.active = true;
                ads.end();
            }
        }
        else
        {
            this.showTips("Not enough cash!");
        }
    }

    public isFull():boolean{
        var max = 0;
        var count = 0;
        for (let i = 0; i < this.rooms.length; i++) {
            for (let j = 0; j < this.rooms[i].seatActorList.length; j++) {
                max++;
                if(this.rooms[i].seatActorList[j]!=null){
                    count++;
                }
            }
        }
        return max == count;
    }
    
    public showStore()
    {
        ads.redirect();
    }


    public showTips(content:string)
    {
        this.clickAudio.volume = 0.5;
        this.clickAudio.playOneShot(this.audioClips[1],1);


        var anim = ResourceManager.spawn("Tips",ResourceManager.getPoolNode("TipsParent")).getComponent(Animation);
        var label = anim.node.children[0].children[0].getComponent(Label);
        label.string = content;
        anim.play("tips@show");
    }

    
    //#region 角色队列

    private InitActorList()
    {
        for (let i = 0; i < 20; i++) {
            //var resName = "UIActor";
            var resName = "UIActor"+randomRangeInt(1,this.prefabCount+1);

            var parent = ResourceManager.getPoolNode("ActorQueueParent");
            var actor = ResourceManager.spawn(resName,null).getComponent(Actor);
            actor.node.eulerAngles = new Vec3(0,0,0);
            actor.node.setParent(parent,true);

            this.actorList.push(actor);
        }
        this.queueMove(0);
    }
    
    public actorCount:number = 99;
    @property(Label)
    public actorCountTxt:Label;

    private shiftActor(){
        var outActor = this.actorList.shift();
        outActor.tween?.stop();
        this.actorCount--;
        this.actorCountTxt.string = `${this.actorCount.toString()}/99`;
        if(this.actorCount == 0)
        {
            this.storePanel.active = true;
        }
        else
        {
            //移出去一个，补一个进来
            var resName = "UIActor"+randomRangeInt(1,this.prefabCount+1);

            var parent = ResourceManager.getPoolNode("ActorQueueParent");
            var actor = ResourceManager.spawn(resName,null).getComponent(Actor);
            actor.node.setParent(null,false);
            actor.node.eulerAngles = new Vec3(0,0,0);
            actor.node.setParent(parent,true);
            actor.node.position = new Vec3(0,-50*19,0);
            this.actorList.push(actor);
        }
        this.queueMove(0.5);
    }
    
    private queueMove(time:number){
        var parent = ResourceManager.getPoolNode("ActorQueueParent")
        for (let i = 0; i < this.actorList.length; i++) {
            var actor = this.actorList[i];

            actor.face(parent.up);
            actor.dotween((_actor)=>{
                _actor.anim.play("walk_bike");
                return tween(_actor.node).to(time,{position:new Vec3(0,i*-50,0)},{ easing: 'linear' }).call(()=>{
                    _actor.anim.play("idle_bike");
                }).start();
            });
        }
    }
    //#endregion

    //#region 相机移动
    @property(Camera)
    public camera:Camera;

    @property(Node)
    public cameraPoints: Node;

    public cameraMove()
    {
        var t = 0.2;
        if(this.count == 1)
        {
            t = 0;
        }
        var targetPoint = this.cameraPoints.children[this.count - 1];

        tween(this.camera).to(t,{orthoHeight:Number(targetPoint.name)}).start();
        tween(this.camera.node).to(t,{worldPosition:targetPoint.worldPosition}).start();

    }
    //#endregion
}
